# -*- coding: utf-8 -*-
import logging

from common import orm
from common.bankcard import handler as bankcard_handler
from common.recharge import db as recharge_db
from common.cache import redis_cache
from common.utils import tz
from common.timer import TIMER_EVENT_TYPE, TimerEvent, EventHandler
from async.async_job import notify_mch
from common.third.tonglue import tonglue_revoke_order


_LOGGER = logging.getLogger('worker')


def submit_routine_event(event_type, delay_ts):
    event_msg = {}
    if not delay_ts:
        return
    expire_ts = tz.now_ts() + delay_ts
    event_id = TimerEvent.submit(event_type, event_msg, expire_ts)
    _LOGGER.info('submit bankcard event e_id[%s] %s' % (event_id, expire_ts))


class CardBalanceHandler(EventHandler):
    ''' 通过同略云API更新卡实时余额 '''

    def process(self, event_msg):
        _LOGGER.info('Run CardBalanceHandler')
        try:
            success = bankcard_handler.fetch_all_card_balance()
            submit_routine_event(TIMER_EVENT_TYPE.FETCH_TONGLUE_BALANCE, 300)
            _LOGGER.info('CardBalanceHandler success')
        except Exception as e:
            _LOGGER.exception('CardBalanceHandler process error.(%s)' % e)
        return True


class CheckBankcardLimit(EventHandler):
    ''' 检查每张卡是否达到限额，并更新限额状态 '''

    def process(self, event_msg):
        _LOGGER.info('Run CheckBankcardLimit')
        try:
            success = bankcard_handler.check_bankcard_limit()
            submit_routine_event(TIMER_EVENT_TYPE.CHECK_BANKCARD_LIMIT, 60)
            _LOGGER.info('CheckBankcardLimit success')
        except Exception as e:
            _LOGGER.exception('CheckBankcardLimit process error.(%s)' % e)
        return True

